package 堆;

import java.util.*;

/**
 * @author TTDB
 * @create 2025/9/23
 */
public class topKFrequent {
     public int[] topKFrequent(int[] nums, int k)
    {
        //统计出现频率
        Map<Integer, Integer> map = new HashMap<>();
        for(int c : nums){
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        //创建小顶堆
        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> map.get(a) - map.get(b));
        for(int key : map.keySet()){
            pq.offer(key);
            if(pq.size() > k){
                pq.poll();
            }
        }
        int[] res = new int[k];
        for(int i = k - 1; i >= 0; i--){
            res[i] = pq.poll();
        }
        return res;
    }
}
